<?php
class ucAction extends baseAction{

	private $_public_action = array('login','register','sina_login','sina_callback','qq_login','qq_callback');

	public function _initialize() {
		parent::_initialize();
		if(!$this->check_login() && !in_array(ACTION_NAME, $this->_public_action)){
			header('Location:'.U('uc/login'));
		}
	}
	function index(){
		header('Location:'.U('uc/share_list'));
	}
	function like_list(){
		$mod=D('like_list');
		$act=$_REQUEST['act'];
		$id=intval($_REQUEST['id']);

		if($act=='del'){
			$this->ajaxReturn($this->like_list_mod->del(intval($_REQUEST['id'])));
		}
		$res=get_favorite('like_list', 40);
		$this->assign('list',$res['list']);
		$this->assign('page',$res['page']);

		$this->display();
	}
	function share_list(){
		$act=$_REQUEST['act'];
		if($act=='del'){
			$this->user_mod->where('id='.$_SESSION['user_id'])->setDec('share_num');
			$this->ajaxReturn($this->items_mod->del(intval($_REQUEST['id'])));
		}
		$res=get_favorite('share_list', 40);
		$this->assign('list',$res['list']);
		$this->assign('page',$res['page']);
		$this->display();
	}
	function account_basic(){

		if (isset($_POST['dosubmit'])) {

			$count=$this->user_mod->where('id!='.$_SESSION['user_id']." and name='".trim($_POST['name'])."'")->count();
			if($count){
				$this->assign('err',array('err'=>0,'msg'=>'昵称已经存在!'));
				$this->display();
				exit;
			}
			$count=$this->user_mod->where('id!='.$_SESSION['user_id']." and email='".trim($_POST['email'])."'")->count();
			if($count>0){
				$this->assign('err',array('err'=>0,'msg'=>'邮箱已经被注册!'));
				$this->display();
				exit;
			}
			$data=$this->user_mod->create();

			if ($_FILES['img']['name'] != '') {
				$upload_list=$this->_upload($_FILES['img']);
				$data['img'] ="http://".$_SERVER['SERVER_NAME'].__ROOT__."/data/user/".$upload_list['0']['savename'];
			}

			$data['brithday']=$_POST['year'].'|'.$_POST['month'].'|'.$_POST['day'];
			$data['address']=$_POST['province'].'|'.$_POST['city'];
			$this->user_mod->save($data);
			$this->assign('user',$this->user_mod->where('id='.$_SESSION['user_id'])->find()) ;
			$this->assign('err',array('err'=>1,'msg'=>'修改成功!'));
		}
		$this->display();
	}
	function account_sns(){
		$res=$this->user_openid_mod->where('uid='.$_SESSION['user_id'])->select();
		foreach ($res as $key=>$val){
			$this->assign('bind_'.$val['type'],true);
		}
		$this->display();
	}
	function account_pwd(){
		if (isset($_POST['dosubmit'])) {
			$passwd=trim($this->user_mod->where('id='.$_SESSION['user_id'])->getField('passwd'));

			if(trim($passwd)!=md5(trim($_POST['passwd']))){
				$this->assign('err',array('err'=>0,'msg'=>'当前密码错误!'));
			}else{
				$data=array('passwd'=>md5(trim($_POST['new_pwd'])));
				$this->user_mod->where('id='.$_SESSION['user_id'])->save($data);
				$this->assign('err',array('err'=>1,'msg'=>'修改成功!'));
			}
		}
		$this->display();
	}
	function account_invitation(){
		$this->assign('share',array(
            'uc_url'=>'http://'.$_SERVER['HTTP_HOST'].__APP__.'/uc/id/'.$_SESSION['user_id'],
            'info'=>'女人天生爱逛街，和我们一起来逛吧！~'.$this->setting["site_domain"]
            ));
            $this->display();
	}
	function get_share_dialog(){
		$this->assign('cate_list',$this->get_cate_list());
		$this->display();
	}
	function items_collect(){
		$itemcollect_mod = D('itemcollect');
		$items_cate_mod = D('items_cate');
		$items_tags_mod = D('items_tags');
		$items_mod = D('items');

		$url = isset($_REQUEST['url']) ? $_REQUEST['url'] : '';
		//!$url && $this->ajaxReturn('', '', 0);
		$url = urldecode($url);

		$itemcollect_mod->url_parse($url);
		$data = $itemcollect_mod->fetch();
		if(!is_array($data)){
			$this->ajaxReturn(array('err'=>'remote_not_exist'));
		}
		$data['item']['item_key']=$data['item']['key'];

		$tags = $items_tags_mod->get_tags_by_title($data['item']['title']);

		$data['item']['cid'] = $items_cate_mod->get_cid_by_tags($tags);
		$data['item']['tags'] = implode(' ', $tags);
		$item_id = $items_mod->where("item_key='" . $data['item']['item_key'] . "'")->getField('id');

		if($item_id){
			$this->ajaxReturn(array('err'=>'yet_exist','url'=>__APP__."?m=item&a=index&id=".$item_id));
		}
		$this->ajaxReturn($data['item']);
	}
	function add_items(){
		$items_mod = D('items');
		$items_cate_mod = D('items_cate');
		$items_site_mod = D('items_site');
		$items_tags_mod = D('items_tags');
		$items_tags_item_mod = D('items_tags_item');

		if (false === $data = $items_mod->create()) {
			$this->ajaxReturn('data_create_error');
		}
		$data['add_time'] = time();
		$data['recommend_start_time']=time();
		$data['recommend_end_time']=time();
		
		$author = isset($_POST['author']) ? $_POST['author'] : '';

		$data['sid'] = $items_site_mod->where("alias='" . $author. "'")->getField('id');
		$item_id = $items_mod->where("item_key='" . $data['item_key'] . "'")->getField('id');
		if ($item_id) {
			$re = $items_mod->where('id=' . $item_id)->save($data);
		} else {
			$new_item_id = $items_mod->add($data);
			$items_cate_mod->where('id='.$data['cid'])->setInc('item_nums');
			$this->user_mod->where('id='.$_SESSION['user_id'])->setInc('share_num');
		}
		if ($new_item_id) {
			$tags =$_POST['tags'];
			if ($tags) {
				$tags_arr = explode(' ', $tags);
				$tags_arr = array_unique($tags_arr);
				foreach ($tags_arr as $tag) {
					$isset_id = $items_tags_mod->where("name='" . $tag . "'")->getField('id');
					if ($isset_id) {
						$items_tags_mod->where('id=' . $isset_id)->setInc('item_nums');
						$items_tags_item_mod->add(array(
                                'item_id' => $new_item_id,
                                'tag_id' => $isset_id
						));
					} else {
						$tag_id = $items_tags_mod->add(array('name' => $tag));
						$items_tags_item_mod->add(array(
                                'item_id' => $new_item_id,
                                'tag_id' => $tag_id
						));
					}
				}
			}
			$items_cate_mod->setInc('item_nums', 1);
		}
		$this->ajaxReturn('success');
	}

	function qq_login(){
		$type=isset($_REQUEST['type'])?$_REQUEST['type']:'callback';
		$_SESSION['state']=	md5(uniqid(rand(), TRUE));
		$redirect_uri=$this->site_root."index.php?m=uc&a=qq_".$type;

		$login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
		.$this->setting['qq_app_key']. "&redirect_uri=".urlencode($redirect_uri)
		. "&state=" . $_SESSION['state'];

		header("Location:$login_url");
	}
	function qq_callback(){

		if($_REQUEST['state'] == $_SESSION['state']) //csrf
		{
			$token_url = "https://graph.qq.com/oauth2.0/token";
			$aGetParam = array(
	            "grant_type"    =>    "authorization_code",
	            "client_id"        =>    $this->setting['qq_app_key'],
	            "client_secret"    =>    $this->setting['qq_app_Secret'],
	            "code"            =>   $_REQUEST["code"],
	            "redirect_uri"    =>  $this->site_root."index.php?m=uc&a=qq_callback"
	            );

	            $res = $this->get($token_url,$aGetParam);

	            if(trim($res)==''){
	            	exit('无法获取认证！<br/>');
	            }
	            if (strpos($res, "callback") !== false)
	            {
	            	$lpos = strpos($res, "(");
	            	$rpos = strrpos($res, ")");
	            	$res  = substr($res, $lpos + 1, $rpos - $lpos -1);
	            	$msg = json_decode($res);
	            	if (isset($msg->error))
	            	{
	            		echo "<h3>error:</h3>" . $msg->error;
	            		echo "<h3>msg  :</h3>" . $msg->error_description;
	            		exit;
	            	}
	            }
	            parse_str($res, $res);
	            $_SESSION["access_token"] = $res['access_token'];
		}
		$url = "https://graph.qq.com/oauth2.0/me";

		$str=$this->get($url,array('access_token'=>$_SESSION['access_token']));

		if (strpos($str, "callback") !== false)
		{
			$lpos = strpos($str, "(");
			$rpos = strrpos($str, ")");
			$str  = substr($str, $lpos + 1, $rpos - $lpos -1);
		}
		$res = json_decode($str);

		$_SESSION['openid']=$res->openid;

		$user_openid=$this->user_openid_mod->where("openid='".$res->openid."'")->find();
		$is_new=false;

		if($user_openid){
			if($this->user_mod->where('id='.$user_openid['uid'])->count()>0){
				$_SESSION['user_id']=$user_openid['uid'];
				$data=array('last_time'=>time(),'last_ip'=>$_SERVER['REMOTE_ADDR']);
				$this->user_mod->where('id='.$_SESSION['user_id'])->save($data);
			}else{
				$this->user_openid_mod->where("openid='".$token['uid']."'")->delete();
				$is_new=true;
			}
		}else{
			$is_new=true;
		}
		if($is_new){
			$url="https://graph.qq.com/user/get_user_info?"
			."access_token=".$_SESSION['access_token']
			."&openid=".$_SESSION['openid']
			."&oauth_consumer_key=".$this->setting['qq_app_key']
			."&format=json";
			$url="https://graph.qq.com/user/get_user_info";
			$param=array(
			 'access_token'=>$_SESSION['access_token'],
			 "openid"=>$_SESSION['openid'],
			 "oauth_consumer_key"=>$this->setting['qq_app_key'],
			 "format"=>'json',
			);

			$res= $this->get($url,$param);

			if($res==false){
			 exit('获取用户信息失败！');
			}
			$res=json_decode($res);
			$qq_info=array('user_info'=>$res);
			$data=array(
                'name'=>$res->nickname,
                'img'=>$res->figureurl_2,
		        'last_time'=>time(),
		        'last_ip'=>$_SERVER['REMOTE_ADDR'],
			    'add_time'=>time(),
			    'ip'=>$_SERVER['REMOTE_ADDR'],
			);

			$_SESSION['user_id']=$this->user_mod->add($data);
			$data=array(
			     'type'=>'qq',
			     'uid'=>$_SESSION['user_id'],
			     'openid'=>$_SESSION['openid'],
			     'info'=>serialize($qq_info),
			);
			$this->user_openid_mod->add($data);
			header('Location:'.U('uc/sign'));exit;
		}
		$_SESSION['login_type']='qq';

		header('Location:'.urldecode($_COOKIE['redirect']));
	}
	function qq_bind(){

		if($_REQUEST['state'] == $_SESSION['state'])
		{

			$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
			. "client_id=" .$this->setting['qq_app_key']
			. "&redirect_uri=" . urlencode($this->site_root."index.php?m=uc&a=qq_callback")
			. "&client_secret=" .$this->setting['qq_app_Secret']
			. "&code=" . $_REQUEST["code"];

			$res = array();
			parse_str(file_get_contents($token_url), $res);
		}
		$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$res['access_token'];
		$str  = file_get_contents($graph_url);
		if (strpos($str, "callback") !== false)
		{
			$lpos = strpos($str, "(");
			$rpos = strrpos($str, ")");
			$str  = substr($str, $lpos + 1, $rpos - $lpos -1);
		}
		$res = json_decode($str);

		$user_openid=$this->user_openid_mod->where("openid='".$res->openid."' and uid=".$_SESSION['user_id'])->find();

		if($user_openid){
			exit("已经绑定!");
		}else{
			$data=array(
                 'type'=>'qq',
                 'uid'=>$_SESSION['user_id'],
                 'openid'=>$res->openid,
                 'info'=>serialize($qq_info),
			);
			$this->user_openid_mod->add($data);
		}
		header('Location:'.U('uc/account_sns'));exit;
	}
	function sns_unbind(){
		$type=$_REQUEST['type'];
		if(!isset($type))exit;
		$this->user_openid_mod->where('uid='.$_SESSION['user_id']." and type='$type'")->delete();
		header('Location:'.U('uc/account_sns'));exit;
	}
	function sina_login(){
		require_once ROOT_PATH.'/includes/saetv2.ex.class.php';
		$type=isset($_REQUEST['type'])?$_REQUEST['type']:'callback';
		$redirect_uri=$this->site_root."index.php?m=uc&a=sina_".$type;

		$o = new SaeTOAuthV2($this->setting['sina_app_key'] ,$this->setting['sina_app_Secret']);
		$login_url=$o->getAuthorizeURL($redirect_uri);

		header("Location:$login_url");
	}

	function sina_callback(){
		require_once ROOT_PATH.'/includes/saetv2.ex.class.php';

		$o = new SaeTOAuthV2($this->setting['sina_app_key'],$this->setting['sina_app_Secret']);

		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] =$this->site_root."index.php?m=uc&a=sina_callback";

			try {
				$token = $o->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {

			}
		}

		$c = new SaeTClientV2( $this->setting['sina_app_key'] ,
		$this->setting['sina_app_Secret'] ,
		$token['access_token'] ,'' );
		if(!$token){
			echo '登录失败!';exit;
		}

		$_SESSION['token'] = $token;
		$_SESSION['access_token']=$token['access_token'];
		$_SESSION['openid']=$token['uid'];
		$user_openid=$this->user_openid_mod->where("openid='".$token['uid']."'")->find();

		$is_new=false;
		if($user_openid){
			if($this->user_mod->where('id='.$user_openid['uid'])->count()>0){
				$_SESSION['user_id']=$user_openid['uid'];
				$data=array('last_time'=>time(),'last_ip'=>$_SERVER['REMOTE_ADDR']);
				$this->user_mod->where('id='.$_SESSION['user_id'])->save($data);
			}else{
				$this->user_openid_mod->where("openid='".$token['uid']."'")->delete();
				$is_new=true;
			}
		}else{
			$is_new=true;
		}
		if($is_new){
			$res=$c->show_user_by_id($token['uid']);
			if($res['error_code']==21321){
				$this->error('新浪微博网站接入审核未通过，无法获取该账户资料！');exit;
			}
			$sina_info=array('user_info'=>$res);
			$data=array(
                'name'=>$res['screen_name'],
                'img'=>$res['profile_image_url'],
				'last_time'=>time(),
                'last_ip'=>$_SERVER['REMOTE_ADDR'],
                'add_time'=>time(),
                'ip'=>$_SERVER['REMOTE_ADDR'],
			);
			$_SESSION['user_id']=$this->user_mod->add($data);
			$data=array(
                 'type'=>'sina',
                 'uid'=>$_SESSION['user_id'],
                 'openid'=>$_SESSION['openid'],
                 'info'=>serialize($sina_info),
			);
			$this->user_openid_mod->add($data);
			header('Location:'.U('uc/sign'));exit;
		}
		$_SESSION['login_type']='sina';
		header('Location:'.urldecode($_COOKIE['redirect']));
	}

	function sina_bind(){
		require_once ROOT_PATH.'/includes/saetv2.ex.class.php';

		$o = new SaeTOAuthV2($this->setting['sina_app_key'],$this->setting['sina_app_Secret']);

		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] =$this->site_root."index.php?m=uc&a=sina_callback";

			try {
				$token = $o->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {

			}
		}

		$c = new SaeTClientV2( $this->setting['sina_app_key'] ,
		$this->setting['sina_app_Secret'] ,
		$token['access_token'] ,'' );
		if(!$token){
			echo '登录失败!';exit;
		}

		$user_openid=$this->user_openid_mod->where("openid='".$token['uid']."' and uid=".$_SESSION['user_id'])->find();

		if($user_openid){
			exit("已经绑定!");
		}else{
			$res=$c->show_user_by_id($token['uid']);
			if($res){
				$sina_info=array('user_info'=>$res);
				$data=array(
                     'type'=>'sina',
                     'uid'=>$_SESSION['user_id'],
                     'openid'=>$token['uid'],
                     'info'=>serialize($sina_info),
				);
				$this->user_openid_mod->add($data);
			}else{
				echo '获取用户信息失败!';exit;
			}
		}
		header('Location:'.U('uc/account_sns'));exit;
	}
	function login(){
		if($this->isAjax()){
			$user=$this->user_mod
			->where("name='".trim($_POST['name'])."' and passwd='".md5(trim($_POST['passwd']))."'")->find();
			if($user){
				$_SESSION['user_id']=$user['id'];
				$this->ajaxReturn(array('err'=>1,'msg'=>'登录成功!'));
			}else{
				$this->ajaxReturn(array('err'=>0,'msg'=>'昵称或密码错误!'));
			}
		}

		if($this->check_login())header('Location:'.U('index/index'));

		if (isset($_POST['dosubmit'])) {
			$user=$this->user_mod
			->where("name='".trim($_POST['name'])."' and passwd='".md5(trim($_POST['passwd']))."'")->find();
			if($user){
				$_SESSION['user_id']=$user['id'];
				header('Location:'.urldecode($_COOKIE['redirect']));
			}else{
				$this->assign('err',array('err'=>0,'msg'=>'昵称或密码错误!'));
			}
		}
		$this->display();
	}
	function register(){
		if($this->check_login()){
			header('location:'.u('index/index'));
		}
		if (isset($_POST['dosubmit'])) {
			$data=$this->user_mod->create();
			$this->assign('data',$data);
			$flag=true;
			if($this->user_mod->where("name='".trim($data['name'])."'")->count()){
				$this->assign('err',array('err'=>0,'msg'=>'昵称已存在!'));
				$flag=false;
			}else if(strlen(trim($data['email']))>0){
				if($this->user_mod->where("email='".trim($data['email'])."'")->count()){
					$this->assign('err',array('err'=>0,'msg'=>'邮箱已经存在!'));
					$flag=false;
				}
			}else if($_SESSION['verify']!=md5($_POST['verify'])){
				$this->assign('err',array('err'=>0,'msg'=>'验证码错误!'));
				$flag=false;
			}
			if($flag){
				$data['ip']=$_SERVER['REMOTE_ADDR'];
				$data['add_time']=time();
				$data['passwd']=md5(trim($data['passwd']));
				$id=$this->user_mod->add($data);
				$_SESSION['user_id']=$id;
				header('location:'.u('uc/index'));
			}
		}
		$this->display();
	}

	function logout(){
		if($_SESSION['login_type']=='sina'){
			$url="https://api.weibo.com/2/account/end_session.json?"
			."access_token=".$_SESSION['access_token']
			."&source".$this->setting['sina_app_key'];
			$res=file_get_contents($url);
		}

		if (isset($_COOKIE[session_name()])) {
			setcookie(session_name(), '', time()-42000, '/');
		}
		session_destroy();

		header('Location:'.urldecode($_COOKIE['redirect']));
	}
	function sign(){
		if (isset($_POST['dosubmit'])) {
			$count=$this->user_mod->where('id!='.$_SESSION['user_id']." and name='".trim($_POST['name'])."'")->count();
			if($count){
				$this->assign('err',array('err'=>0,'msg'=>'昵称已经存在!'));
				$this->display();
				exit;
			}
			if(strlen(trim($_POST['passwd']))<6){
				$this->assign('err',array('err'=>0,'msg'=>'密码至少为6位!'));
				$this->display();
				exit;
			}
			$data=array(
			     'name'=>trim($_POST['name']),
			     'passwd'=>md5(trim($_POST['passwd'])),
			);
			$this->user_mod->where('id='.$_SESSION['user_id'])->save($data);
			header('Location:'.U('uc/index'));
		}
		$this->display();
	}
	function add_comment(){
		$uid=$_POST['uid'];
		if($uid!=$_SESSION['user_id'])exit;
		$data=$this->items_comments_mod->create();
		$data['add_time']=time();
		$data['info']=$this->remove_html($data['info']);

		$this->items_comments_mod->add($data);

		$items_mod = D('items');
		$items_mod->where('id=' . $data['items_id'])->setInc('comments');

		$this->ajaxReturn('提交成功!');
	}
	private function _upload() {
		import("ORG.Net.UploadFile");
		$upload = new UploadFile();
		$upload->maxSize = 3292200;
		$upload->savePath = ROOT_PATH.'/data/user/';

		$upload->saveRule = uniqid;
		if (!$upload->upload()) {
			$this->error($upload->getErrorMsg());
		} else {
			$uploadList = $upload->getUploadFileInfo();
		}
		return $uploadList;
	}
	function share_result_dialog(){
		$this->display();
	}
}
